﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;

namespace DouYin.Open.Platform
{
    public class CheckSign : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            try
            {
                var query = dataset.GetJsonObject("query");
                var timestamp = query.GetJsonObjectStringValue("timestamp", "0");

                long milliseconds = 0;
                long.TryParse(timestamp, out milliseconds);
                DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                time = time.AddMilliseconds(milliseconds * 1000).ToLocalTime();
                var minutes = (DateTime.Now - time).TotalMinutes;
                if (minutes > 5 || minutes < -5)
                    throw new Exception();
                JToken sign = new GetSign().Invoke(dataset);
                if (sign == null || string.IsNullOrWhiteSpace(sign.ToString()) || !sign.ToString().Equals(query.GetJsonObjectStringValue("sign")))
                    throw new Exception();
            }
            catch (Exception ex)
            {
                LogHelper.Info("Authentication fail: " + ex.Message);
                throw new Exception("@0001");
            }

            return true;
        }
    }
}
